import {requestBody8080} from "@/Network/requestBody8080";
import {requestChat} from "@/Network/requestChat";

export function directChineseChat(q:string) {
    let data = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content":q+"（中文回答且不能超过50字）"}]
    }
    let url = "/chat/completions"
    return requestChat({
        url: url,
        method: 'post',
        data
    })
}

export function findAllUserChatByAccountName(accountName:string){
    let url = "/UserChatController/findAllByAccountName"
    let params = {
        accountName:accountName
    }
    return requestBody8080({
        url:url,
        method:"post",
        headers:{
            "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"
        },
        params
    })
}

export function addUserChat(accountName, question, answer) {
    let data = {
        "accountName": accountName,
        "answer": answer,
        "question":question
    }
    let url = "/UserChatController/addUserChat"
    return requestBody8080({
        url: url,
        method: 'post',
        data
    })
}

export function streamChineseChat(q:string) {
    let data = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content":q+"（中文回答且不能超过50字）"}],
        "stream": true,
    }
    let url = "/chat/completions"
    return requestChat({
        url: url,
        method: 'post',
        responseType:"stream",
        data
    })
}

export async function streamFetchChineseChat(q:string){
    try{
        // 发送请求
        let response = await fetch("https://api.closeai-proxy.xyz/v1/chat/completions",
            {
                method: "post",
                responseType: "stream",
                headers: {
                    "Authorization": "Bearer " + 'sk-tHy9pL8JW1QIPM3GMNGCQIitk3rjKtq8j0k2HxGJ6dh9qCvC',
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    "model": "gpt-3.5-turbo",
                    "messages": [{"role": "user", "content": q+" (中文回答且不能超过50字)"}],
                    "stream":true
                }),
            }
        );
        // ok字段判断是否成功获取到数据流
        if (!response.ok) {
            console.log("Network response was not ok");
        }
        // 用来获取一个可读的流的读取器（Reader）以流的方式处理响应体数据
        const reader = response.body.getReader();
        // 将流中的字节数据解码为文本字符串
        const textDecoder = new TextDecoder();
        let result = true;
        let sqlValue = ''
        while (result) {
            // done表示流是否已经完成读取  value包含读取到的数据块
            const { done, value } = await reader.read();
            if (done) {
                result = false;
                break;
            }
            // 拿到的value就是后端分段返回的数据，大多是以data:开头的字符串
            // 需要通过decode方法处理数据块，例如转换为文本或进行其他操作
            textDecoder
                .decode(value)
                .split("\n")
                .forEach((val) => {
                    if (!val) return;
                    try {
                        // 后端返回的流式数据一般都是以data:开头的字符，排除掉data:后就是需要的数据,并将其序列化JSON。parse方便操作键值
                        // 具体返回结构可以跟后端约定
                        let text = val?.replace("data:", "") || ""
                        console.log(text)
                        let singleAns = JSON.parse(text)
                        // console.log( "输出返回的:"+singleAns.choices[0].delta.content);
                        if(singleAns.choices[0].finish_reason !="stop"){//未结束时为null
                            sqlValue += singleAns.choices[0].delta.content;
                            console.log(sqlValue)
                        }
                    } catch (err) {}
                });
        }
        console.log(sqlValue,'输出最终返回答案')
    } catch(err) {}
}
